// pages/myBottles/myBottles.js
Page({
  data: {
    myBottles: [],
    repliedBottles: [],
    isLoading: false,
    hasMore: true,
    pageSize: 10,
    currentPage: 1,
    showDeleteModal: false,
    deletingBottleId: null,
    showLoading: false
  },

  onLoad: function () {
    this.loadMyBottles();
  },

  onShow: function () {
    // 每次显示页面时重新加载数据
    this.loadMyBottles(true);
  },

  // 加载我的漂流瓶
  loadMyBottles: function (refresh = false) {
    if (this.data.isLoading) return;

    if (refresh) {
      this.setData({
        myBottles: [],
        currentPage: 1,
        hasMore: true
      });
    }

    this.setData({ isLoading: true });

    // 调用云函数获取我的瓶子
    wx.cloud.callFunction({
      name: 'getMyBottles',
      data: {
        openid: wx.getStorageSync('openid') || ''
      },
      success: res => {
        if (res.result && res.result.code === 0) {
          let myBottles = res.result.myBottles || [];
          // 给每个漂流瓶加 formattedTime 字段
          myBottles = myBottles.map(bottle => ({
            ...bottle,
            formattedTime: this.formatTime(new Date(bottle.time))
          }));
          // 按时间排序（最新在前）
          myBottles.sort((a, b) => new Date(b.time) - new Date(a.time));
          // 分页
          const startIndex = (this.data.currentPage - 1) * this.data.pageSize;
          const endIndex = startIndex + this.data.pageSize;
          const paginatedBottles = myBottles.slice(startIndex, endIndex);
          const hasMore = endIndex < myBottles.length;
          this.setData({
            myBottles: refresh ? paginatedBottles : [...this.data.myBottles, ...paginatedBottles],
            hasMore: hasMore,
            currentPage: this.data.currentPage + 1,
            isLoading: false
          });

          // 加载我回复过的漂流瓶
          this.loadRepliedBottles();
        } else {
          wx.showToast({ title: res.result.msg || '加载失败', icon: 'none' });
          this.setData({ isLoading: false });
        }
      },
      fail: err => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        this.setData({ isLoading: false });
      }
    });
  },

  // 时间格式化
  formatTime: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  // 加载我回复过的漂流瓶
  loadRepliedBottles: function () {
    try {
      // 从本地缓存获取我回复过的漂流瓶
      let repliedBottles = wx.getStorageSync('repliedBottles') || [];

      // 按时间排序（最新的在前）
      repliedBottles.sort((a, b) => new Date(b.replyTime) - new Date(a.replyTime));

      this.setData({ repliedBottles });
    } catch (e) {
      console.error('加载回复过的漂流瓶失败:', e);
    }
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.loadMyBottles(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (!this.data.isLoading && this.data.hasMore) {
      this.loadMyBottles();
    }
  },

  // 显示删除确认对话框
  showDeleteConfirm: function (e) {
    const bottleId = e.currentTarget.dataset.id;
    if (!bottleId) {
      wx.showToast({ title: '找不到瓶子ID', icon: 'none' });
      return;
    }
    this.setData({
      showDeleteModal: true,
      deletingBottleId: bottleId
    });
  },

  // 关闭删除确认对话框
  closeDeleteModal: function () {
    this.setData({
      showDeleteModal: false,
      deletingBottleId: null
    });
  },

  // 确认删除
  confirmDelete: function () {
    const { deletingBottleId } = this.data;

    if (!deletingBottleId) return;

    this.setData({
      showLoading: true,
      showDeleteModal: false
    });

    // 调用云函数删除
    wx.cloud.callFunction({
      name: 'deleteBottle',
      data: {
        id: deletingBottleId,
        openid: wx.getStorageSync('openid') || ''
      },
      success: res => {
        if (res.result && res.result.code === 0) {
          wx.showToast({ title: '删除成功', icon: 'success' });
          // 重新加载
          this.setData({
            myBottles: [],
            currentPage: 1,
            hasMore: true,
            showLoading: false
          });
          this.loadMyBottles(true);
        } else {
          wx.showToast({ title: res.result.msg || '删除失败', icon: 'none' });
          this.setData({ showLoading: false });
        }
      },
      fail: err => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        this.setData({ showLoading: false });
      }
    });
  },

  // 查看漂流瓶详情
  viewBottleDetail: function (e) {
    const bottleId = e.currentTarget.dataset.id;
    const isMine = e.currentTarget.dataset.ismine;

    wx.navigateTo({
      url: `/pages/bottleDetail/bottleDetail?id=${bottleId}&isMine=${isMine}`
    });
  },

  // 前往扔漂流瓶页面
  goToThrow: function () {
    wx.navigateTo({
      url: '/pages/throw/throw'
    });
  }
});    